package com.tanhua.admin.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.pojo.Analysis;
import com.tanhua.model.vo.AnalysisSummaryVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

//统计数据的类
@Service
public class AnalysisService {

    @Resource
    private LogMapper logMapper;

    @Resource
    private AnalysisMapper analysisMapper;

    //日期的格式
    private final String dateFormat = "yyyy-MM-dd";

    //统计当天的用户使用数据
    public void analysis() {
        //1 获取今天和昨天的日期  yyyy-MM-dd
        String today = DateUtil.format(new Date(), dateFormat);
        String yesterday = DateUtil.yesterday().toString(dateFormat);

        DateTime todayDate = DateUtil.parse(today, dateFormat);

        //2 实现数据统计的查询
        //新注册用户数
        Integer numRegistered = logMapper.findCountByLogTimeAndType(today, "0102");
        //登陆次数
        Integer numLogin = logMapper.findCountByLogTimeAndType(today, "0101");

        //活跃用户数
        Integer numActive = logMapper.findNumActive(today);

        //次日留存用户数
        Integer numRetention1d = logMapper.findNumRetention1d(today, yesterday);

        //3 查询当天统计的数据对象
        Analysis analysis = analysisMapper.selectOne(Wrappers.lambdaQuery(Analysis.class)
                .eq(Analysis::getRecordDate, todayDate));

        //4 判断当天的统计数据是否存在
        if (analysis == null) {
            // 如果不存在就新增
            analysis = new Analysis();
            analysis.setRecordDate(todayDate);
            analysis.setNumRegistered(numRegistered);
            analysis.setNumLogin(numLogin);
            analysis.setNumActive(numActive);
            analysis.setNumRetention1d(numRetention1d);

            analysisMapper.insert(analysis);
        } else {
            // 如果存在就进行修改
            analysis.setNumRegistered(numRegistered);
            analysis.setNumLogin(numLogin);
            analysis.setNumActive(numActive);
            analysis.setNumRetention1d(numRetention1d);

            analysisMapper.updateById(analysis);
        }

    }

    //概要统计信息
    public AnalysisSummaryVo getSummary() {
        //1 创建vo对象
        AnalysisSummaryVo vo = new AnalysisSummaryVo();

        //2 查询今天的和昨天的统计数据
        String today = DateUtil.format(new Date(), dateFormat);
        String yesterday = DateUtil.yesterday().toString(dateFormat);

        Date todayDate = DateUtil.parse(today, dateFormat);
        Date yesterdayDate = DateUtil.parse(yesterday, dateFormat);

        Analysis todayAnalysis = analysisMapper.selectOne(Wrappers.lambdaQuery(Analysis.class)
                .eq(Analysis::getRecordDate, todayDate));
        Analysis yesterdayAnalysis = analysisMapper.selectOne(Wrappers.lambdaQuery(Analysis.class)
                .eq(Analysis::getRecordDate, yesterdayDate));

        //3 设置数据到vo中
        //累计用户数 cumulativeUsers  所有的注册用户数之和
        vo.setCumulativeUsers(analysisMapper.cumulativeUsers());

        //今日新增用户数量 newUsersToday
        vo.setNewUsersToday(Long.valueOf(todayAnalysis.getNumRegistered()));
        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌 newUsersTodayRate
        vo.setNewUsersTodayRate(rate(
                todayAnalysis.getNumRegistered(), yesterdayAnalysis.getNumRegistered())
        );

        //今日登录次数 loginTimesToday
        vo.setLoginTimesToday(Long.valueOf(todayAnalysis.getNumLogin()));
        //今日登录次数涨跌率，单位百分数，正数为涨，负数为跌 loginTimesTodayRate
        vo.setLoginTimesTodayRate(rate(
                todayAnalysis.getNumLogin(), yesterdayAnalysis.getNumLogin()
        ));

        //今日活跃用户数量 activeUsersToday
        vo.setActiveUsersToday(Long.valueOf(todayAnalysis.getNumActive()));
        //今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌 activeUsersTodayRate
        vo.setActiveUsersTodayRate(rate(
                todayAnalysis.getNumActive(), yesterdayAnalysis.getNumActive()
        ));

        //4 返回结果 vo
        return vo;

    }

    //根据今日的数据和昨日的数据，计算涨跌率
    private Integer rate(int today, int yesterday) {
        int result = 0;

        if (yesterday == 0) {
            //如果前一天的数据量为0   今天没多一个用户的操作，增长率就增加100
            result = today * 100;
        } else {
            result = (today - yesterday) * 100 / yesterday;
        }
        return result;
    }

}
